<template>
  <el-container>
    <el-header>
      <el-input
        v-model="queryInfo.title"
        placeholder="课程标题"
        style="width: 220px"
      />
      <el-button
        type="defult"
        style="margin-top: 10px;margin-left: 10px;"
        @click="contentChange"
      >查询</el-button>
      <el-button
        type="primary"
        style="margin-top: 10px"
        @click="addCourse"
      >添加
      </el-button>

    </el-header>

    <el-main>

      <el-table
        ref="questionTable"
        v-loading="loading"
        highlight-current-row
        :border="true"
        :data="datasources"
        tooltip-effect="dark"
        style="width: 100%;"
        row-key="id"
        :tree-props="{children: 'children'}"
        :show-overflow-tooltip="true"
      >

        <!-- <el-table-column
          align="center"
          prop="questionBank.bankName"
          label="ID"
        /> -->

        <el-table-column
          align="center"
          prop="title"
          label="课程标题"
        />

        <el-table-column
          align="center"
          prop="description"
          label="课程简介"
        >
          <template slot-scope="scope">
            <span>{{ !!scope.row.description?scope.row.description:'-' }}</span>
          </template>
        </el-table-column>

        <el-table-column
          align="center"
          prop="order"
          label="排序号"
        >
          <template slot-scope="scope">
            <span>{{ !!scope.row.order?scope.row.order:'-' }}</span>
          </template>
        </el-table-column>

        <el-table-column
          align="center"
          prop="teacherName"
          label="课程讲师"
        >
          <template slot-scope="scope">
            <span>{{ !!scope.row.teacherName?scope.row.teacherName:'-' }}</span>
          </template>
        </el-table-column>

        <el-table-column
          align="center"
          prop="coverFileName"
          label="课程封面"
        >
          <template slot-scope="scope">
            <el-button
              v-if="!!scope.row.coverFileName"
              type="text"
              @click="openCourse(scope.row.coverFileName)"
              style="white-space: pre-wrap;word-wrap: break-word;overflow-wrap: break-word;"
            >{{scope.row.coverFileName}}</el-button>
            <span v-else>-</span>
          </template>
        </el-table-column>

        <el-table-column
          label="操作"
          align="center"
        >
          <template slot-scope="scope">
            <el-button
              type="text"
              @click="openEditUI(scope.row.id)"
            >修改</el-button>
            <el-button
              type="text"
              @click="deleteUser(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>

      </el-table>
      <!--分页-->
      <el-pagination
        style="margin-top: 25px"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pageNo"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="queryInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      />

      <el-dialog
        title="课程封面"
        :visible.sync="courseImgVisible"
        width="650px"
        :destroy-on-close=true
        :before-close="handleCloseCourseImg"
      >
        <div>
          <img
            :src="getImageURL"
            alt="Image"
            v-if="imageData"
            style="width:100%;height:85%"
          />
          <div
            v-else
            style="text-align:center"
          >
            <div>
              <i
                class="el-icon-loading"
                style="font-size:80px;color:#409EFF"
              />
            </div>
            <div>
              <span style="color:#409EFF;font-size:17px">加载中，请稍候</span>
            </div>
          </div>

        </div>
      </el-dialog>

    </el-main>
  </el-container>
</template>

<script>
import getCourse from "@/api/course";
import utils from "@/utils/utils";
import { getToken } from "@/utils/auth";
import axios from "axios";

export default {
  name: "QuestionBankManage",
  data() {
    return {
      token: getToken(),
      courseImgVisible: false,
      imageData: null, // 用于存储图片数据的变量
      queryInfo: {
        title: "",
        pageNo: 1,
        pageSize: 10,
      },
      datasources: [],
      // 被选中的表格的信息
      selectedTable: [],
      // 所有题库信息
      questionBankInfo: [],
      // 当前被选中的操作
      operation: "",
      loading: true,
      // 所有的题库条数
      total: 0,
      // 添加题库的对话框
      addTableVisible: false,
      // 添加题库的表单信息
      addForm: {
        bankName: "",
      },
      // 添加表单的数据校验规则
      addFormRules: {
        bankName: [
          {
            required: true,
            message: "请输入题库名称",
            trigger: "blur",
          },
        ],
      },
    };
  },
  created() {
    this.getBankInfo();
  },
  computed: {
    getImageURL() {
      if (this.imageData) {
        // 将二进制流数据转换为 Base64 格式的 URL
        const base64Data = btoa(
          new Uint8Array(this.imageData).reduce(
            (data, byte) => data + String.fromCharCode(byte),
            ""
          )
        );
        return `data:image/jpeg;base64,${base64Data}`;
      }
      return null;
    },
  },
  methods: {
    //删除
    deleteUser(row) {
      console.log(row);
      let obj = {
        id:row.id,
        type: !!row.teacherName
          ? "1"
          : !!row.chapterName
          ? "2"
          : !!row.sectionName
          ? "3"
          : "",
      };
      this.$confirm("该课程或章节底下存在课时，将全部删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          getCourse.delete(obj).then((res) => {
            console.log("res---------", res);
            if (res.code === 20000) {
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              this.getBankInfo();
            } else {
              this.$notify({
                title: "Tips",
                message: res.message,
                type: "error",
                duration: 2000,
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //点击课程封面
    openCourse(fileName) {
      this.courseImgVisible = true;
      this.fetchImageData({ fileName });
    },

    //关闭课程封面弹窗
    handleCloseCourseImg() {
      this.courseImgVisible = false;
      this.imageData = null;
    },

    // 文件预览
    fetchImageData(obj) {
      axios
        .get(`/file/preview/${obj.fileName}`, {
          responseType: "arraybuffer",
          headers: { "X-Token": this.token },
        })
        .then((response) => {
          // 将二进制流数据存储在 imageData 变量中
          this.imageData = response.data;
        })
        .catch((error) => {
          console.error(error);
        });
    },

    //添加课程
    addCourse() {
      this.$router.push({ path: "/examManage/courseAdd" });
    },

    // 获取所有的课程信息
    getBankInfo() {
      getCourse.getCourseList(this.queryInfo).then((res) => {
        console.log("res---------", res);
        if (res.code === 20000) {
          let arr = JSON.parse(JSON.stringify(res.data.data));
          arr = arr.map((item) => {
            item = {
              ...item.course,
              children: item.characterList,
            };
            item.children = item.children.map((item1, index1) => {
              item1 = {
                ...item1,
                id: item1.id,
                title: item1.chapterName,
                order: item1.chapterOrder,
                children: item1.sectionList,
              };
              item1.children = item1.children.map((item2, index2) => {
                item2 = {
                  ...item2,
                  // id: `id+${item1.id}`,
                  title: item2.sectionName,
                  order: item2.sectionOrder,
                };
                return item2;
              });
              return item1;
            });
            return item;
          });
          console.log("arr-------", arr);
          this.datasources = arr;
          this.total = res.data.total;
          this.loading = false;
        } else {
          this.$notify({
            title: "Tips",
            message: res.message,
            type: "error",
            duration: 2000,
          });
        }
      });
    },
    // 查询内容变化
    contentChange() {
      this.getBankInfo();
    },

    // 分页插件的大小改变
    handleSizeChange(val) {
      this.queryInfo.pageSize = val;
      this.getBankInfo();
    },
    // 分页插件的页数
    handleCurrentChange(val) {
      this.queryInfo.pageNo = val;
      this.getBankInfo();
    },
  },
};
</script>

<style scoped lang="scss">
@import "../../assets/css/teacher/questionBankManage";
</style>
